import Vue from 'vue'
import { getToken, getCsrfToken } from '@/utils/auth'
import Utils from '@/libs/framework/util'
import Constant from '@/libs/framework/constant'
import qs from 'qs'

const baseURL = process.env.VUE_APP_BASE_API

const fly = require("flyio");
fly.config.baseURL = baseURL
const Fly = require("flyio/dist/npm/fly")
const newFly = new Fly;
newFly.config = fly.config;

fly.config.headers = {
  "content-type": "application/x-www-form-urlencoded"
}
fly.interceptors.request.use((request) => {
  if (request.method === 'POST' || request.method === 'post') {
    request.body = qs.stringify(request.body)
  }
  let csrfToken = getCsrfToken()
  if (csrfToken) {
    request.headers = {
      ...request.headers
    }
    request.headers[Constant.token.csrfToken] = csrfToken
    
  }
  return request;
});

fly.interceptors.response.use(
  (response) => { //不要使用箭头函数，否则调用this.lock()时，this指向不对
    return response.status == 200 ? response.data : response;
  },
  (err) => {
    if (err.status = 403) {
      // newFly.post('/getCsrfToken').then(res => {
      //   localStorage.setItem("csrfToken", res.data.token);
      // })
    }
  }
)

Vue.prototype.$http = fly;